const express = require('express');
const router = express.Router();
const pool = require('../config/bd');
const { v4: uuidv4 } = require('uuid'); // 导入后使用
const jwt = require('jsonwebtoken');

//用户登录
router.post('/login', async (req, res) => {
  const { username, password } = req.body;

  // 1. 必填字段校验
  if (!username || !password) {
    return res.status(400).json({ error: '缺少账号或密码' });
  }

  try {
    // 2. 查询用户是否存在
    const [users] = await pool.query(
      'SELECT * FROM user WHERE username = ? LIMIT 1',
      [username]
    );

    // 3. 用户不存在时的处理
    if (users.length === 0) {
      return res.status(401).json({ error: '用户不存在' });
    }

    const user = users[0];

    // 4. 密码验证
    if (user.password !== password) {
      return res.status(401).json({ error: '密码错误' });
    }

    // 5. 生成JWT令牌
    const token = jwt.sign(
      { userId: user.id },
      process.env.JWT_SECRET,
      { expiresIn: '24h' }
    );

    // 6. 返回登录成功响应
    res.json({
      success: true,
      message: '登录成功',
      data: {
        userId: user.id,
        familyID: user.family_id,
        token: token,
        username: user.username,
      }
    });

  } catch (err) {
    console.error('登录失败:', err);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// 创建新用户
router.post('/registered', async (req, res) => {
  const { username, password } = req.body;
  const nickname = '用户' + username
  if (!username || !password) {
    return res.status(400).json({ error: '账号或密码为输入' });
  }

  try {

    const userId = uuidv4(); // 使用uuid库生成

    await pool.query(
      'INSERT INTO user (id, username, password, nickname) VALUES (?, ?, ?, ?)',
      [userId, username, password, nickname]
    );

    // 查询新插入的 UUID
    const [rows] = await pool.query(
      'SELECT id,family_id FROM user WHERE username = ? ORDER BY created_at DESC LIMIT 1',
      [username]
    );


    const token = jwt.sign(
      { userId: userId },
      process.env.JWT_SECRET,
      { expiresIn: '24h' }
    );


    res.status(201).json({
      success: true,
      message: '注册成功',
      data: {
        userId: rows[0].id,
        familyID: rows[0].family_id,
        token: token
      }
    });
  } catch (err) {
    console.error('POST Error:', err);
    res.status(500).json({
      success: false,
      error: "用户注册失败"
    });
  }
});

module.exports = router;